from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from app.crud.userCrud import (
    get_user, get_users, create_user, update_user, delete_user, get_users_with_count
)
from app.schemas.userSchema import User, UserCreate, PaginatedUserResponse
from app.database import get_db
from typing import Optional  # 确保导入 Optional
from app.auth import get_current_active_user  # 导入认证依赖

router = APIRouter(prefix="/api/v1", tags=["用户管理"])

@router.post("/users", response_model=User,summary="用户新增",description="用户新增描述")
async def create_user_endpoint(
        user: UserCreate,
        db: AsyncSession = Depends(get_db)
):
    """创建新的日志记录

    - **action**: 操作类型（如"create", "update", "delete"）
    - **details**: 操作详情（JSON字符串或详细描述）
    """
    return await create_user(db, user=user)

@router.get("/users", response_model=PaginatedUserResponse)
async def read_users(
    skip: int = 0,
    limit: int = 100,
    action: Optional[str] = None,  # 新增：按 action 过滤
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)  # 👈 添加认证依赖
):
    """获取日志列表（支持分页和条件查询）

    - **skip**: 跳过的记录数（默认0）
    - **limit**: 每页返回的最大记录数（默认100）
    - **action**: 按操作类型过滤（可选）
    """
    #print(current_user.username)
    #users = await PaginatedUserResponse(db, skip=skip, limit=limit, action=action)
    data = await get_users_with_count(db, skip=skip, limit=limit, action=action)
    return PaginatedUserResponse(**data)
    #return users

# @router.get("/users/", response_model=List[User])
# async def read_users(
#         skip: int = 0,
#         limit: int = 100,
#         db: AsyncSession = Depends(get_db)
# ):
#     """获取日志列表（分页）
#
#     - **skip**: 跳过的记录数（默认为0）
#     - **limit**: 每页返回的最大记录数（默认为100）
#     """
#     users = await get_users(db, skip=skip, limit=limit)
#     return users


@router.get("/users/{user_id}", response_model=User)
async def read_user(
        user_id: int,
        db: AsyncSession = Depends(get_db)
):
    """根据ID获取单个日志记录

    - **user_id**: 要查询的日志ID
    """
    db_user = await get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user


@router.put("/users/{user_id}", response_model=User)
async def update_user_endpoint(
        user_id: int,
        user: UserCreate,
        db: AsyncSession = Depends(get_db)
):
    """更新日志记录

    - **user_id**: 要更新的日志ID
    - **action**: 新的操作类型
    - **details**: 新的操作详情
    """
    db_user = await update_user(db, user_id=user_id, user=user)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user


@router.delete("/users/{user_id}", response_model=User)
async def delete_user_endpoint(
        user_id: int,
        db: AsyncSession = Depends(get_db)
):
    """删除日志记录

    - **user_id**: 要删除的日志ID
    """
    db_user = await delete_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user